package com.sky.wsp.license.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSONUtil;
import com.sky.wsp.license.conf.KeyToolConfig;
import com.sky.wsp.license.conf.LicenseConfig;
import com.sky.wsp.license.utils.*;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 在此输入描述
 * @date 2024/6/24
 */
@RestController
public class IndexController {
    @Resource
    private KeyToolConfig keyToolConfig;
    @Resource
    private LicenseConfig licenseConfig;

    @GetMapping("keytool")
    public KeyToolConfig keyToolConfig() {
        return keyToolConfig;
    }

    @GetMapping("license")
    public LicenseConfig licenseConfig() {
        return licenseConfig;
    }

    @GetMapping("sign")
    public String sign() {
        String xml = XmlUtil.beanToXml(LicenseConfig.class, licenseConfig);
        System.out.println(xml);

        KeyStore keyStore = KeyUtil.loadKeyStore(keyToolConfig);
        PrivateKey key = KeyUtil.getPrivateKey(keyStore, keyToolConfig);
        if (null == key) {
            return "获取私钥失败！";
        }
        String base64String = Base64.toBase64String(xml.getBytes(StandardCharsets.UTF_8));
        X509Certificate certificate = CertificateUtil.getCertificate(keyStore, keyToolConfig.getAlias());
        String sign = SignatureUtil.sign(certificate, key, xml);
        System.out.println(sign);
        String certificateStr = CertificateUtil.certificateToStr(certificate);
        System.out.println(certificateStr);
        File license = new File("license.lic");
        try {
            IoUtil.write(new FileOutputStream(license),true, (sign + "." + base64String).getBytes());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return certificateStr;
    }

    @GetMapping("verify")
    public boolean verify(String certificateStr) {
        String license = FileReader.create(new File("license.lic")).readString();
        String[] split = license.split("\\.");
        String sign = split[0];
        String json = new String(Base64.decode(split[1]), StandardCharsets.UTF_8);
        X509Certificate certificate = CertificateUtil.strToCertificate(certificateStr);
        boolean verify = SignatureUtil.verify(certificate, json, sign);
        System.out.println(verify);
        return verify;
    }
}
